package com.risk.management.controller;

import com.risk.management.dto.Result;
import com.risk.management.entity.Project;
import com.risk.management.entity.User;
import com.risk.management.service.ProjectService;
import com.risk.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 项目控制器
 */
@Controller
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private UserService userService;

    /**
     * 项目列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<Project> projects = projectService.getAllProjects();
        
        // 为每个项目获取项目经理信息
        for (Project project : projects) {
            if (project.getManagerId() != null) {
                User manager = userService.getUserById(project.getManagerId());
                if (manager != null) {
                    model.addAttribute("managerName_" + project.getId(), manager.getRealName());
                }
            }
        }
        
        model.addAttribute("projects", projects);
        return "project/list";
    }

    /**
     * 我的项目页面 - 使用Spring Security获取当前用户
     */
    @GetMapping("/my")
    public String myProjects(Model model, @AuthenticationPrincipal UserDetails userDetails) {
        List<Project> projects;
        if (userDetails != null) {
            User user = userService.getUserByUsername(userDetails.getUsername());
            if (user != null) {
                if (user.getRole() == 1) {
                    // 管理员查看所有项目
                    projects = projectService.getAllProjects();
                } else if (user.getRole() == 2) {
                    // 项目经理查看自己管理的项目
                    projects = projectService.getProjectsByManagerId(user.getId());
                } else {
                    // 团队成员查看参与的项目 (这里简化处理，实际应该查询用户参与的项目)
                    projects = projectService.getAllProjects();
                }
            } else {
                projects = projectService.getAllProjects();
            }
        } else {
            projects = projectService.getAllProjects();
        }
        model.addAttribute("projects", projects);
        return "project/my";
    }

    /**
     * 项目详情页面
     */
    @GetMapping("/{id}")
    public String detail(@PathVariable Long id, Model model) {
        Project project = projectService.getProjectById(id);
        if (project == null) {
            return "redirect:/project/list";
        }
        model.addAttribute("project", project);
        
        // 获取项目经理信息
        if (project.getManagerId() != null) {
            User manager = userService.getUserById(project.getManagerId());
            model.addAttribute("manager", manager);
        }
        
        return "project/detail";
    }

    /**
     * 新增项目页面
     */
    @GetMapping("/add")
    public String add(Model model) {
        // 获取所有项目经理
        List<User> managers = userService.getUsersByRole(2);
        model.addAttribute("managers", managers);
        return "project/add";
    }

    /**
     * 新增项目 - 加强数据验证和错误处理
     */
    @PostMapping("/add")
    @ResponseBody
    public Result<Void> add(@RequestBody Project project) {
        // 数据验证
        if (project == null) {
            return Result.error("项目数据不能为空");
        }
        
        if (project.getName() == null || project.getName().trim().isEmpty()) {
            return Result.error("项目名称不能为空");
        }
        
        // 如果有指定项目经理，验证该用户是否存在
        if (project.getManagerId() != null) {
            User manager = userService.getUserById(project.getManagerId());
            if (manager == null) {
                return Result.error("指定的项目经理不存在");
            }
        }
        
        try {
            boolean success = projectService.addProject(project);
            if (success) {
                return Result.success();
            } else {
                return Result.error("添加项目失败");
            }
        } catch (Exception e) {
            return Result.error("系统错误：" + e.getMessage());
        }
    }

    /**
     * 编辑项目页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        Project project = projectService.getProjectById(id);
        if (project == null) {
            return "redirect:/project/list";
        }
        model.addAttribute("project", project);
        
        // 获取所有项目经理
        List<User> managers = userService.getUsersByRole(2);
        model.addAttribute("managers", managers);
        
        return "project/edit";
    }

    /**
     * 编辑项目 - 加强数据验证
     */
    @PostMapping("/edit")
    @ResponseBody
    public Result<Void> edit(@RequestBody Project project) {
        // 数据验证
        if (project == null || project.getId() == null) {
            return Result.error("项目数据不完整");
        }
        
        if (project.getName() == null || project.getName().trim().isEmpty()) {
            return Result.error("项目名称不能为空");
        }
        
        // 验证项目是否存在
        Project existingProject = projectService.getProjectById(project.getId());
        if (existingProject == null) {
            return Result.error("要编辑的项目不存在");
        }
        
        try {
            boolean success = projectService.updateProject(project);
            if (success) {
                return Result.success();
            } else {
                return Result.error("更新项目失败");
            }
        } catch (Exception e) {
            return Result.error("系统错误：" + e.getMessage());
        }
    }

    /**
     * 删除项目
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Result<Void> delete(@PathVariable Long id) {
        try {
            boolean success = projectService.deleteProject(id);
            if (success) {
                return Result.success();
            } else {
                return Result.error("删除项目失败");
            }
        } catch (Exception e) {
            return Result.error("系统错误：" + e.getMessage());
        }
    }

    /**
     * 更新项目状态
     */
    @PostMapping("/status/{id}/{status}")
    @ResponseBody
    public Result<Void> updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        // 验证状态值是否有效
        if (status < 1 || status > 4) {
            return Result.error("无效的项目状态值");
        }
        
        try {
            boolean success = projectService.updateProjectStatus(id, status);
            if (success) {
                return Result.success();
            } else {
                return Result.error("更新项目状态失败");
            }
        } catch (Exception e) {
            return Result.error("系统错误：" + e.getMessage());
        }
    }
} 